package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Project;
import com.kaishengit.entity.User;
import com.kaishengit.entity.UserPro;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class UserProDao {
	private DBHelp<UserPro> db = new DBHelp<UserPro>();
	
	public void save(UserPro up){
		String sql = "INSERT INTO t_user_project (t_user_id,t_project_proId,role) VALUES (?,?,?) ";
		db.executeSQL(sql, up.getUserId(),up.getProId(),up.getPower());
	}
	
	public UserPro findByUseridAndProId(String userid, String proId) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT t_user_id,t_project_proId,role,tu.id,tu.username,tu.password,tu.email,tu.pic,tp.proId,tp.proName,tp.describe,tp.createTime FROM t_user_project AS tup ");
		sql.append("LEFT JOIN t_user AS tu ON tu.id=tup.t_user_id ");
		sql.append("LEFT JOIN t_project AS tp ON tp.proId=tup.t_project_proId ");
		sql.append("WHERE tup.t_user_id=? AND tup.t_project_proId=?");
		
		return db.executeQueryForObject(sql.toString(), new UserProRowMapper() , userid,proId);
	}
	
	private class UserProRowMapper implements RowMapper<UserPro> {

		public UserPro mapRow(ResultSet rs) throws SQLException {
			UserPro up = new UserPro();
			up.setUserId(rs.getString("t_user_id"));
			up.setProId(rs.getString("t_project_proId"));
			up.setPower(rs.getString("role"));
			
			User user = new User();
			user.setId(rs.getString("id"));
			user.setUsername(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			user.setEmail(rs.getString("email"));
			user.setPic(rs.getString("pic"));
			
			up.setUser(user);
			
			Project project = new Project();
			project.setProId(rs.getString("proId"));
			project.setProName(rs.getString("proName"));
			project.setDescribe(rs.getString("describe"));
			project.setCreateTime(rs.getLong("createTime"));
			
			up.setProject(project);
			
			return up ;
		}
		
	}

	public void delete(String proId) {
		String sql = "DELETE FROM t_user_project WHERE t_project_proId=?";
		db.executeSQL(sql, proId);
	}

	
	
}
